/**
 * 
 */
package com.ideeli.webextractor.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ideeli.webextractor.domain.Headers;
import com.ideeli.webextractor.utils.FileHelper;

/**
 * @author spaida
 *
 */
public class GenerateCSVServiceImpl implements GenerateCSVService {
	
	private static final Logger logger = Logger.getLogger(GenerateCSVServiceImpl.class);
	private String dirPath;

	/* (non-Javadoc)
	 * @see com.ideeli.webextractor.service.GenerateCSVService#generateCSV()
	 */
	@Override
	public void generateCSV(List<Map<Headers,String>> headerValList) throws Exception 
	{
		logger.warn("Start generateCSV");
		
		StringBuilder strBuilder= new StringBuilder("");
		//Building header row
		for(Headers h: Headers.values())
		{
			strBuilder.append(h.getVal());
			strBuilder.append(",");
		}
		strBuilder.delete(strBuilder.lastIndexOf(","),strBuilder.length());
		strBuilder.append("\r\n");
		//Building value rows
		if(headerValList==null)
			return;
		
		for(Map<Headers,String> valueMap:headerValList)
		{
			for(Headers h: Headers.values())
			{
				String value=valueMap.get(h);
				
				if(value!=null)
					strBuilder.append(value);
				
				strBuilder.append(",");
			}
			strBuilder.append("\r\n");
			
		}
		
		strBuilder.delete(strBuilder.lastIndexOf(","),strBuilder.length());
		strBuilder.append("\r\n");
		generateFile(strBuilder.toString());

	}
	
	public void generateFile(String content)
	{
		 
		logger.warn("Start generateFile");
		Date date=new Date();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd_HHmmss-SSS");
		String fileName=sdf.format(date);
		try 
		{
			String filePath=dirPath+fileName+".csv";
			FileHelper.writeFile(filePath, content);
		} 
		catch (Exception e) 
		{
			logger.error(e);
			e.printStackTrace();
		}
		logger.info(content);
	}
	
	public void generateDir() throws Exception
	{
		logger.warn("Start generateFile");
		Date date=new Date();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd_HHmmss");
		String dirName=sdf.format(date);
		try 
		{
			dirPath="c:\\users\\spaida\\c\\data\\"+dirName+"\\";
			if("sa".equals(System.getProperty("user.name")))
			{
				dirPath="S:\\data\\csv\\"+dirName+"\\";
			}
			
			File file=new File(dirPath);
			
			if(!file.exists())
			{
				file.mkdir();
				logger.info("dir created:"+dirPath);
			}
			
		} 
		catch (Exception e) 
		{
			logger.error(e);
			e.printStackTrace();
		}
		
	}

}
